<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="35%"
    top="13vh"
    destroy-on-close
    :before-close="closeUserMoveDialogHandle"
    :close-on-click-modal="false"
    class="user-move-dialog"
  >
    <el-form :model="userForm" :rules="userRules" ref="userForm" label-width="85px" @keyup.enter.native="submitHandle">
      <el-form-item v-show="userForm.moveMode === 0" label="用户名称">
        <span>{{ user.username }}</span>
      </el-form-item>
      <el-form-item label="所属部门">
        <span :style="{ color: themeColor }">{{ user.deptName }}</span>
      </el-form-item>
      <el-form-item label="新部门" prop="nextDeptId">
        <tree-select :value="userForm.nextDeptId"
                     :options="deptTree"
                     :disabled="buttonLoad"
                     show-count
                     clearValueText="清除选择"
                     :normalizer="normalizer"
                     @select="deptTreeChangeHandle"
                     placeholder="请选择父级部门" />
      </el-form-item>
      <el-form-item label="切换原因" prop="moveRemark">
        <el-input
          v-model="userForm.moveRemark"
          type="textarea"
          rows="4"
          maxlength="250"
          resize="none"
          show-word-limit
          placeholder="请输入切换原因">
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeUserMoveDialogHandle(false)">取消</el-button>
      <el-button :disabled="buttonLoad" type="primary" @click="submitHandle">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  // 树形选择插件
  import TreeSelect from '@riophae/vue-treeselect'
  // 树形插件样式
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    name: "user-move",
    components: { TreeSelect },
    props: {
      // 弹出框是否显示
      dialogVisible: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        // 弹出框标题
        dialogTitle: undefined,
        // 用户对象
        user: {
          // 用户名称
          username: undefined,
          // 原部门名称
          deptName: undefined
        },
        // 用户表单对象
        userForm: {
          // 用户主键数组
          userIds: undefined,
          // 原所属部门主键
          preDeptId: undefined,
          // 新部门主键
          nextDeptId: undefined,
          // 切换模式[0-单个用户 1-批量切换 2-全部切换]
          moveMode: undefined,
          // 切换原因
          moveRemark: ''
        },
        // 部门树数据列表
        deptTree: [],
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,
        // 用户表单校验规则
        userRules: {
          nextDeptId: [
            { required: true, message: '请选择新部门', trigger: 'blur' }
          ],
          moveRemark: [
            { required: true, message: '切换原因不能为空', trigger: 'blur' }
          ],
        }
      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      },
    },
    methods: {
      /**
       * 初始化用户切换部门弹出框方法
       * @param {Object} user     用户对象
       * @param {string} deptId   部门主键
       * @param {string} deptName 部门名称
       */
      initUserMoveDialog(user, deptId, deptName) {
        // console.log('user', user)
        let _user = this.user;
        let _userForm = this.userForm;
        if (!user) {
          this.dialogTitle = '部门用户集体切换部门'

          _user.deptName = deptName;

          _userForm.preDeptId = deptId;
          _userForm.moveMode = 2;
        } else {
          this.dialogTitle = '用户切换部门'

          _user.username = user.username;
          _user.deptName = user.deptName;

          _userForm.userIds = [ user.userId ];
          _userForm.preDeptId = user.deptId;
          _userForm.moveMode = 0;
        }

        this.getDeptTree()
      },
      /**
       * 获取部门数据树方法
       */
      getDeptTree() {
        // 开始部门树加载
        this.buttonLoad = true;
        this.$axios.$get('/sys/dept/children/tree')
          .then(({ data }) => {
            this.deptTree.push(data);
          })
          .catch(() => {})
          .finally(() => {
            // 部门树加载结束
            this.buttonLoad = false;
          })
      },
      /**
       * 用户切换部门确定事件
       */
      submitHandle() {
        this.$refs.userForm.validate((valid) => {
          if (!valid) {
            return false;
          }
          let userForm = this.userForm;
          if (userForm.preDeptId === userForm.nextDeptId) {
            this.notify('', '温馨提示', '新所属部门不能与原所属部门一致。');
            return false;
          }
          let url = userForm.moveMode === 0 ? '/sys/user-dept/flow/one/move' : '/sys/user-dept/flow/all/move'

          // 开始 单个/全体 用户切换部门
          this.buttonLoad = true;
          this.$axios.$post(url, userForm)
            .then(() => {
              let message = userForm.moveMode === 0 ? '单个用户切换部门操作成功' : '部门用户集体切换操作成功';
              this.notify('success', '操作成功', message);

              this.closeUserMoveDialogHandle(true);
            })
            .catch(() => {})
            .finally(() => {
              // 单个/全体 用户切换部门结束
              this.buttonLoad = false;
            })
        });
      },
      /**
       * 部门树数据转化成插件可识别数据
       * @param node
       * @returns {{children, id: (string|(function(): string)|*), label}}
       */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.deptId,
          label: node.deptName,
          isDisabled: node.disabled,
          children: node.children
        };
      },
      /**
       * 部门树选择项发生改变事件
       * @param node        部门选择树选中节点
       * @param instanceId
       */
      deptTreeChangeHandle(node, instanceId) {
        let userForm = this.userForm
        userForm.nextDeptId = node.deptId
        // 清除校验状态
        this.$refs.userForm.clearValidate(['nextDeptId'])
      },
      /**
       * 关闭用户切换部门弹出框事件
       * @param {boolean|function} bool 是否刷新父级组件
       */
      closeUserMoveDialogHandle(bool) {
        this.dialogTitle = undefined;
        this.user = {
          username: undefined,
          deptName: undefined
        };
        // 清空表单校验信息
        this.$refs.userForm.clearValidate()
        this.userForm = {
          userId: undefined,
          preDeptId: undefined,
          nextDeptId: undefined,
          moveMode: undefined,
          moveRemark: ''
        };
        // 清理部门树数据
        this.deptTree = [];
        // 清理角色数据列表
        this.roleList = [];

        // 此处判断触发事件是否是弹出框自带关闭事件
        if (typeof bool === 'function') {
          bool = false
        }
        // 向上传递事件
        this.$emit('close-user-move-dialog', bool)
      }
    }
  }
</script>

<style scoped>
  .user-move-dialog >>> .el-dialog__body {
    padding: 10px 20px;
  }
</style>
